use dshell::prompt::ShellPrompt;
use once_cell::sync::Lazy;
use std::sync::RwLock;
use std::io::{self, Write};
use std::process::Command;

pub static SHELL_PROMPT: Lazy<RwLock<ShellPrompt>> = Lazy::new(||{
	let prompt = ShellPrompt::new();
	RwLock::new(prompt)
});

fn main() 
{
    loop {
		print!("{}", SHELL_PROMPT.read().unwrap().prompt());
		io::stdout().flush().unwrap();
		let mut cmd = String::new();
		io::stdin().read_line(&mut cmd).unwrap();
		match cmd.trim() {
			"quit" => {
				break;
			}
			_ => {
				let mut parts = cmd.split_whitespace();
				if let Some(program) = parts.next() {
					let args: Vec<&str> = parts.collect();

					let status = Command::new(program)
						.args(&args)
						.spawn()
						.and_then(|mut child| child.wait());

					match status {
						Ok(status) => {
							if !status.success() {
								eprintln!("Process exited with status: {}", status);
							}
						}
						Err(e) => {
							eprintln!("Failed to run {}: {}", program, e);
						}
					}
				}
			}
		}
	}
}
